﻿$(document).ready(function(){
	
	
    // Slider das Thumbs dos produtos.
    $('#product ul.thumbs').DasluProductSlider( {  } );
    
    // Criando a UI de seleção de tamanho
    $('#product #espec_0_opcao_0').jQSelect({ rotulo : "Selecione uma op&ccedil;&atilde;o", selectfirst : false });
    
	$(document).ajaxComplete(function(event,request, settings){ 
	
		$('#product .about .especifications .price').css({ 'visibility' : 'visible' });
		$('#product .about .especifications .price-sliced').css({ 'visibility' : 'visible' });
	
		if($('#product .apresentacao #show .producutsoldout').length > 0){
			$('#product .apresentacao #show .producutsoldout').remove();
		}
	
		if ( $('#product .unavailable-button:visible').size() > 0  )  {
		
			//$('#product .unavailable-button:visible').css({ 'visibility' : 'hidden' });
			$('#product .about .especifications .price').css({ 'visibility' : 'hidden' });
			$('#product .about .especifications .price-sliced').css({ 'visibility' : 'hidden' });
			$('#product .about .especifications .price .valor-por').css({ 'visibility' : 'hidden' });
			
			Cufon.replace("#product .unavailable-button", {
				fontFamily: 'Proxima Nova Rg'
			});
			
			$('#product .apresentacao #show').append('<span class="producutsoldout"></span>');
		}else{
			$('#product .about .especifications .price').css({ 'visibility' : 'visible' });
			$('#product .about .especifications .price-sliced').css({ 'visibility' : 'visible' });
			$('#product .about .especifications .price .valor-por').css({ 'visibility' : 'visible' });
		}
        
        if ( $('#product #likeitbox #resenha .media em span:contains(nenhum)').size() > 0 ){
            $('#product #likeitbox #resenha .media em span:contains(nenhum)').html( $('#product #likeitbox #resenha .media em span:contains(nenhum)').html().replace('nenhum voto','Seja o primeiro <b>a amar esta pe&ccedil;a<b/>'));
        }
        if ( $('#product #likeitbox #resenha .media em span:contains(votos)').size() > 0 ){
            $('#product #likeitbox #resenha .media em span:contains(votos)').html( $('#product #likeitbox #resenha .media em span:contains(votos)').html().replace('votos','Pessoas <b>amaram esta pe&ccedil;a</b>'));
        }
        if ( $('#product #likeitbox #resenha .media em span:contains(voto)').size() > 0 ){
            $('#product #likeitbox #resenha .media em span:contains(voto)').html( $('#product #likeitbox #resenha .media em span:contains(voto)').html().replace('voto','Pessoa <b>amou esta pe&ccedil;a</b>'));
        }
        
        $(".other-payment-method-ul").find("li").css("display", "none");
        $(".other-payment-method-ul").find("li:first-child").css("display", "list-item");

	});
    
    if ( $('#stamps:empty').size() > 0 ) {
        
        $('#stamps').remove();
        
    }
	
    if ( $('.especifications .specification').size() == 0 ) {
    
        $('.especifications h2:first').css({ 'visibility' : 'hidden' });
    
    }
    
   
    $('#usewith li, #otherlooks li, #mostview li, #daslulove li, #lastviews li').live('mouseenter',function() {
		$(this).find('span:not(.soldmini)').stop().fadeTo('fast',1);
	});
	$('#usewith li, #otherlooks li, #mostview li, #daslulove li, #lastviews li').live('mouseleave', function() {
		$(this).find('span:not(.soldmini)').stop().fadeTo('fast',0);
	});
    
    
    
    //#########################################################
    
    
  
    
    $('#product .about .especifications .colors ul li ul').find('li:eq(1)').remove();
    
	$("#usewith ul, #otherlooks ul, #mostview ul, #daslulove ul, #lastviews ul").find("li").each(function(){
		var originalText = $(this).find("a span.produto-nome").text();
		if(originalText.length > 25){
			var shortText = originalText.substr(0, 25);
			if(shortText.charAt(25) != " "){
				shortText = shortText.substr(0, shortText.lastIndexOf(" "));
			}
			$(this).find("li a span.produto-nome").text(shortText + " ...");
		}
	});
	
	$(".apresentacao #show #include").append('<span class="zoomthumb"> </span>');
	
	var videoUrl;
	//CARACTERISTICAS( VIDEO, MUST HAVE, LOOK DA SEMANA
	if( $("#caracteristicas .value-field").length>0 ){
		
		var lancamento = false;
		var limited_edition = false;
		
		$("#caracteristicas .name-field").each(function(){
			
			
		
			if( $(this).text().toLowerCase() == "mania" ){
				$("#stamp-daslu-mania").css("display","block");
				createSeal("img_mania.png","#stamps");
			}
			if( $(this).text().toLowerCase() == "must have" ){
				if($("#stamp-daslu-mania").is(":visible")){
					$("#stamp-daslu-mania").css("display","none");
				}
				$("#stamp-must-have").css("display","block");
				createSeal("img_mustHave.png","#stamps");
				
			}
			if( $(this).text().toLowerCase() == "limited edition" ){
				limited_edition = true;
			}
			if( $(this).text().toLowerCase() == "lançamento" ){
				lancamento = true;
			}
			
			if( $(this).text().toLowerCase() == "look da semana" ){
				createSeal("img_lookDaSemana.png","#stamps");
			}
			
			if( /^http:\/\//.test( $(this).text().toLowerCase() ) ){
				videoUrl = $(this).text();
				videoUrl = videoUrl.replace("http://www.youtube.com/watch?v=","");
				videoUrl = videoUrl.replace("www.youtube.com/watch?v=","");
				videoUrl = videoUrl.replace("youtube.com/watch?v=","");
				setTimeout(createEmbedVideoThumb,1,"/Control/ArquivoExibir.aspx?NomeArquivo=video-thumb.jpg","ul.thumbs",( "http://www.youtube.com/v/" + videoUrl + "?version=3&amp;hl=pt_BR&amp;rel=0" ));
			}
		});
		
		if(lancamento == true && limited_edition == true){
			createSeal("img_lancamento_limitedEdition.png",".apresentacao #show");
		}else{
			if(lancamento == true){
				createSeal("img_lancamento.png",".apresentacao #show");
			}else{
				if(limited_edition == true){
					createSeal("img_limitedEdition.png",".apresentacao #show");
				}
			}
		}
	}
	
	// Adiciona "VER MEDIDAS"
	$(".usage").append("<h3 class='description closed'>Ver medidas</h3>");
	$("<div class='descriptioncontent' id='ver-medidas' style='display:none;'></div>").appendTo(".usage");
	$("#ver-medidas").append("<table></table>");
	$(".Modelo-Veste, .Modelo-Mede").parent().clone().appendTo("#ver-medidas table");
	$("#ver-medidas .Modelo-Veste, #ver-medidas .Modelo-Mede").css("display", "table-cell");
	
	if($("#product_color").find(".colors ul li").length == 0){
		$("#product_color").css("visibility", "hidden");
	}
	
	//PRODUCT IMAGE ZOOM
	$("#show #include #image .image-zoom #image-main").mouseover(function(){
		setTimeout(superZoom_init,100);
	});
	
	$('#indications').appendTo('#main');
	
	//GIFT LIST 
	var giftListUrl = $("#product .apresentacao #show .thumbs li a img").eq(0).attr("src");
	$(".giftList-wrapper .giftList-content .image").attr("src",giftListUrl);
	
	$(".giftList-wrapper .giftlistinsertsku .giftlistinsertsku-lists li:not(.wishlist-title)").css("display","none");
	
	setTimeout(wishlist_init,1);
	
	$(".giftList-wrapper .giftlistinsertsku ul").prepend( $("<li></li>").attr("class","wishlist-title").append( $("<a></a>").text("Selecione") ) );
	$(".giftList-content").find("a[href='/lista/criar']").attr("href", "/Site/Login.aspx");
	
	$("#product .about .especifications .wishlish a").click(function(){
		$(".giftList-wrapper").fadeIn("slow");
	});
	
	//fechar
	$(".giftList-wrapper .giftList-content a.wishlist-fechar").click(function(){
		$(".giftList-wrapper").fadeOut("slow");
	});	
	
	//Ao selecionar Wish List
	$(".giftlistinsertsku-lists li:not('.wishlist-title') a").live("click", function(){
		setTimeout(function(){
			$(".giftList-wrapper .giftList-content a.wishlist-fechar").trigger('click');
		}, 2000);
	});
	/*
	//remover a palavra POR do preco da wishlist
	$(".giftList-wrapper span.price em.valor-por").text( $(".giftList-wrapper span.price em.valor-por").text().replace(/Por\s+/gi,"") );
	
	if ( $('#product .about .especifications .price em.valor-por').size() > 0 ) {
	
		$('#product .about .especifications .price em.valor-por').html( $('#product .about .especifications .price em.valor-por').html().replace("Por ","") );
	
	}
	*/
   
	if ( $('#product .unavailable-button:visible').size() > 0  )  {
		
		
		$('#product .unavailable-button:visible').css({ 'visibility' : 'hidden' });
		$('#product .about .especifications .price').css({ 'visibility' : 'hidden' });
		$('#product .about .especifications .price-sliced').css({ 'visibility' : 'hidden' });
		
		$('#product .apresentacao #show').append('<span class="producutsoldout"></span>');
	
	}
	
	$('#product .about .especifications .price-sliced ul li:not(".vista"):last').show();
	
	$('.preco-a-vista').remove();

    // Seletor de Cores
	

    
    /*  $('.colors ul li:not(li li)').each(function() {
		
            var anchor = $(this).find('a');
            var colorElement = $(this).find('li');
            var colorName = $(this).find('li').text();
            
            colorName = colorName.toLowerCase();
            
            colorName = colorName.replace(new RegExp('[áàâã]','gi'), 'a');
            colorName = colorName.replace(new RegExp('[éèê]','gi'), 'e');
            colorName = colorName.replace(new RegExp('[íìî]','gi'), 'i');
            colorName = colorName.replace(new RegExp('[óòôõ]','gi'), 'o');
            colorName = colorName.replace(new RegExp('[úùû]','gi'), 'u');
            colorName = colorName.replace(new RegExp('[ç]','gi'), 'c');
            colorName = colorName.replace(new RegExp('[\ \)\(\_]', 'gi'), '-');
            colorName = colorName.replace(new RegExp('[^a-z0-9\-]', 'gi'), '');
            
            
            $(anchor).html('<span>' + colorName + '</span>' );
            $(anchor).addClass( colorName );
            $(anchor).attr({ 'title' : colorName });
            $(anchor).css({ 'background-image' : "url('/Control/ArquivoExibir.aspx?NomeArquivo=prodcor-" +  colorName + ".jpg')" });
            
            if ( $.browser.msie ) {
                $(anchor).attr({"style" : $(anchor).attr("style").replace("&#61;","") });
            }
            
            //Cleaning de LI
            $(colorElement).html(""); 
            $(anchor).appendTo( $(colorElement) );
            //$(this).css({ 'background' : 'url(/Control/ArquivoExibir.aspx?NomeArquivo=prodcor-' +  $(this).attr('class') + '.jpg) 0 0  repeat' });
        
        });
    */
    
	$("#likeitbox").click(function(){
		$(this).find("#rtAvaliacao_Star_5").trigger("click");
	});
	
	$('#show .thumbs li a').each(function () {
	
		$(this).append('<span class="zoomthumb"> </span>')
	
	});
	
	$('#product #likeitbox #resenha').mouseenter(function() {

        $(this).find('#rtAvaliacao_Star_5').show();

    });
	
    $('#product #likeitbox #resenha').mouseleave(function() {

        $(this).find('#rtAvaliacao_Star_5').hide();

    });
    
	
	// Eventos da págna de produtos.
	$('h3.description').click(function() {
	
		if( $(this).next().is(":hidden")) {
			
			$(this).next().slideDown();
			$(this).removeClass('closed');
			
		}else {
			
			$(this).next().slideUp();
			$(this).addClass('closed');
			
		}
	
	});
    
    
    
	if ( $('#product #likeitbox .wrap li span').size() > 0 ){

    var quantity = $('#product #likeitbox .wrap li span').html();

    if ( quantity == 0 ) {

		$('#product #likeitbox .peopleslove').html('Seja o primeiro a amar esta pe&ccedil;a!');    

    }else if ( quantity == 1 ) {
    
		$('#product #likeitbox .peopleslove').html('Pessoa ama esta pe&ccedil;a');  

    }else {

		$('#product #likeitbox .peopleslove').html('Pessoas amaram esta pe&ccedil;a'); 

		}

	}
	
	$('#product #likeitbox .wrap').mouseenter(function() {

		$(this).find(".giftlistinsertsku-button").stop().fadeTo('fast',1);
		
	});	
	
	$('#product #likeitbox .wrap').mouseleave(function() {

		$(this).find(".giftlistinsertsku-button").stop().fadeTo('fast',0);
		
	});	
	// end here

	if($("#caracteristicas").find("td.value-field.Video-do-Produto").length > 0){
		$("#JQRollInstance .thumbs li:first-child").before("<li><span id='video-thumb'><img src='/Control/ArquivoExibir.aspx?NomeArquivo=video-thumb.jpg' alt='' /></span></li>");
	}
	
	$("#video-thumb").click(function(){
		$("<div id='overlay' />").appendTo("body").css({"opacity": "0", "display":"block"}).animate({"opacity": "0.75"}, 200,function(){
			$("#caracteristicas").find("td.value-field.Video-do-Produto iframe").clone(false).attr("id","youtube").appendTo("body");
			$("#youtube").css("margin-left", (($("#youtube").width() / 2) * (-1)));
			$("#youtube").css("margin-top", (($("#youtube").height() / 2) * (-1)));
			$("<img src='/Control/ArquivoExibir.aspx?NomeArquivo=img_modal_closebutton.jpg' id='youtube-close' alt='Fechar' />").appendTo("body");
			$("#youtube-close").css("margin-top", ((($("#youtube").height() / 2) * (-1))));
			$("#youtube-close").css("margin-right", ((($("#youtube").width() / 2) * (-1)) - 39));
		});
	
		return false;
	});
	
	$("#youtube-close").live("click", function(){
		$("#youtube, #youtube-close").remove();
		$("#overlay").animate({"opacity": "0"}, 200, function(){ $(this).remove(); });
		$(this).remove();
	});
	
	$(".addWishlist").hover(function(){
		if($(this).find("#tooltip").length == 0){
			$(this).append("<span id='tooltip'>" + $(this).text() + "</span>");
			$(this).append("<span id='tooltip_arrow'></span>");
			
			var width = (($(this).find("span#tooltip").outerWidth())/2) * (-1);
			$(this).find("span#tooltip").css({"opacity":"0", "margin-left": width});
			$(this).find("span#tooltip_arrow").css({"opacity":"0"});
			$(this).find("span#tooltip, span#tooltip_arrow").css({"opacity":"1"});
			
		}
	}, function(){
		if($(this).find("#tooltip").length == 1){
			$(this).find("span#tooltip, span#tooltip_arrow").css({"opacity":"0"});
			$(this).find("span#tooltip, span#tooltip_arrow").remove();
		}
	});
	
	$("#support").mouseenter(supportOver);
	$("#support").mouseleave(supportOut);
	
	$("#support").bind("click", function(){
		if($(this).find("#helpbox #content").is(":hidden")){
			$(this).find("#helpbox .help").css("display", "none");
			$(this).find("#helpbox #content").css("display", "block");
			
			var contentPos = ($(this).find("#helpbox #content").outerWidth() * (-1)) / 2

			$(this).find("#helpbox #content").css("margin-left", contentPos);
			$(this).unbind("mouseenter mouseleave");
		}else{
			$(this).bind({mouseenter: supportOver, mouseleave: supportOut});
		}
	});
	
	//Exibe o menor parcelamento disponível
	$(".other-payment-method-ul").find("li").css("display", "none");
	$(".other-payment-method-ul").find("li:first-child").css("display", "list-item");
	
	//Estilo dos tamanhos caso só tenha um tamanho
	if($(".topic.Tamanho.Roupas").find("li").length <= 3){
		$(".topic.Tamanho.Roupas").find(".select").addClass("size");
		//$(".topic.Tamanho.Roupas").css("overflow", "hidden");
	}
    
    if ( $('#ver-medidas .name-field').size() == 0 ) {
    
        $('.description:contains("Ver medidas")').css({ 'visibility' : 'hidden' });
        $('#ver-medidas').css({ 'visibility' : 'hidden' });
    
    }
    
    $('.bread-crumb li a').each(function(){
    
        if ( $(this).attr('title') == "Casa e Gifts" ){
        
            $('#product .about .especifications h2:first').css({ 'visibility' : 'hidden' }); 
            $('#product .about .especifications .Details').css({ 'visibility' : 'hidden' }); 
            $('#product .about .especifications .Casa').css({ 'visibility' : 'hidden' }); 
            
        }
    
    });
    
    
    $('.wishlist-title a').html("Selecione uma lista");
    $('.giftlistinsertsku').before('<a href="/lista/criar" id="createlistbutton">Criar uma lista</a>');
    
    //#########################################################
    
    
    Cufon.replace('#stamp-must-have .text-big, #stamp-daslu-mania .text-big', {
        fontFamily: 'Knockout'
    });
    
    Cufon.replace('#usewith li a span, #otherlooks li a span, #mostview li a span, #daslulove li a span, #lastviews li a span', {
		fontFamily: 'Proxima Nova Rg'
	});
    
    Cufon.replace('.produto h1', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#product .about h2', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#product .about .share', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#product .about .share', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#indications h3', {
        fontFamily: 'Proxima Nova Rg'
    });
	
    
    
        $('.colors ul li:not(li li)').each(function() {
		
            var anchor = $(this).find('a');
            var colorElement = $(this).find('li');
            var colorName = $(this).find('li').text();
            
            colorName = colorName.toLowerCase();
            
            colorName = colorName.replace(new RegExp('[áàâã]','gi'), 'a');
            colorName = colorName.replace(new RegExp('[éèê]','gi'), 'e');
            colorName = colorName.replace(new RegExp('[íìî]','gi'), 'i');
            colorName = colorName.replace(new RegExp('[óòôõ]','gi'), 'o');
            colorName = colorName.replace(new RegExp('[úùû]','gi'), 'u');
            colorName = colorName.replace(new RegExp('[ç]','gi'), 'c');
            colorName = colorName.replace(new RegExp('[\ \)\(\_]', 'gi'), '-');
            colorName = colorName.replace(new RegExp('[^a-z0-9\-]', 'gi'), '');
            
            
            $(anchor).append('<span>' + colorName + '</span>');
            $(anchor).addClass( colorName );
            $(anchor).attr({ 'title' : colorName });
            $(anchor).css({ 'background-image' : "url(/Control/ArquivoExibir.aspx?NomeArquivo=prodcor-" +  colorName + ".jpg)" });
            
            if ( $.browser.msie ) {
                $(anchor).attr({"style" : $(anchor).attr("style").replace("&#61;","") });
            }

            $(colorElement).empty(); 
            $(colorElement).append($(anchor));
            
        });
    
    
});


function supportOver(){
	$(this).find("#helpbox, #helpbox .help").css("display","block");
	$(this).find("#helpbox #content").css("display", "none");
	
	var titleLeftPos = ($(this).find("#helpbox .help").outerWidth() * (-1)) / 2;
	var titleTopPos = 
	$(this).find("#helpbox .help").css("margin-left", titleLeftPos);
}
	
function supportOut(){
	$("#helpbox, #helpbox .help, #helpbox #content").css("display","none");
}


function createEmbedVideo(videoUrl, destination){
	if( $("#embed-wrapper").length==0 ){
		var object = 
			"<div id='embed-wrapper'>"+
				"<object width='469' height='469'>"+
					"<param name='movie' value='"+videoUrl+"'></param>"+
					"<param name='allowFullScreen' value='true'></param>"+
					"<param name='allowscriptaccess' value='always'></param>"+
					"<param name='wmode' value='transparent'></param>"+
					"<embed src='"+videoUrl+"' wmode='transparent' type='application/x-shockwave-flash' width='469' height='469' allowscriptaccess='always' allowfullscreen='true'></embed>"+
				"</object>"+
			"</div>";
		$(destination).append( $(object) );
	}
}

function createEmbedVideoThumb(imgSrc, ulDes, url){
	$(ulDes).prepend(
			$("<li></li>").append( $("<a></a>").attr({"id":"embed-video","href":"javascript:void(0)"}).append( $("<img />").attr("src",imgSrc) ) )
	);
	
	//EVENTOS
	$("#product .apresentacao #show .thumbs li a").bind("click", function() {
		$("#embed-wrapper").remove();
		if( $(this).attr("id") == "embed-video" ){
			createEmbedVideo( url, "#include #image");
			$("#embed-wrapper").show();
		}
	});
}

function createSeal(sealImg,target) {
	var img = "<img class='seal-img' src='/Control/ArquivoExibir.aspx?NomeArquivo="+sealImg+"' />";
	$(target).append( $(img) );
}

function superZoom_init(){
    if( $(window).width()<=1024 ){
        $(".jqZoomWindow").delay(100).css("left","507px");
    }else{
        $(".jqZoomWindow").css("left","678px");
    }
}

function wishlist_init(){
	$(".giftList-wrapper .giftlistinsertsku .giftlistinsertsku-lists li.wishlist-title").click(function(){
		$(this).parent().find("li:not(.wishlist-title)").slideToggle("slow");
	});
}

